package com.shop.cereshop.admin.job;

import cn.hutool.core.collection.CollUtil;
import com.shop.cereshop.admin.service.wallet.WalletTransactionService;
import com.shop.cereshop.commons.domain.wallet.CereBuyerWallet;
import com.shop.cereshop.commons.utils.TimeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Order(8)
@Slf4j
public class WalletJob {

    @Resource
    private WalletTransactionService walletTransactionService;

    @XxlJob("syncCancelFreeze")
    @Scheduled(cron = "0 0/5 * * * ?")//5分钟执行一次
    public void syncCancelFreeze() {
        log.info("开始执行自动解冻功能");
        System.out.println("开始执行自动解冻功能");

        //1、游标分页查询所有已过期但未解冻的用户
        int pageSize = 1000;
        Long lastId = 0L;//初始游标
        String now = TimeUtils.yyMMddHHmmss();
        try {
            while (true) {
                List<CereBuyerWallet> expiredRecords =  walletTransactionService.findExpiredFreeze(now, pageSize, lastId);
                if (CollUtil.isEmpty(expiredRecords)) {
                    break;
                }

                //2、批量解冻用户
                //将已过期的记录列表的钱包id放到一个集合中
                List<Long> walletIds = expiredRecords.stream().map(CereBuyerWallet::getWalletId).collect(Collectors.toList());
                int rows = walletTransactionService.batchUnfreeze(walletIds);
                log.info("解冻用户成功，解冻数量：{}", rows);

                //3、更新游标
                lastId = expiredRecords.get(expiredRecords.size() - 1).getWalletId();
            }
        } catch (Exception e) {
            log.error("自动解冻功能执行异常", e);
        }
    }
}
